<?php
/**
 * Author: wl
 * Email: 446399160@qq.com
 * DateTime: 2017/05/01 13:31
 */

namespace app\modules\v1\models;
use yii\db\ActiveRecord;
use Yii;

class Weixinupload extends ActiveRecord{

	private $appId;
	private $appSecret;
	
	public function __construct() {
		$this->appId 		= Yii::$app->params['appid'];
		$this->appSecret 	= Yii::$app->params['appsecret'];
	}
	
	public function getSignPackage() {
		$jsapiTicket = $this->getJsApiTicket();
		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol 	= (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url 		= Yii::$app->params['weixinphotourl'];       //"http://wx.78dk.com/weixin/obj/src/views/photo.html";
		$timestamp 	= time();
		$nonceStr 	= $this->createNonceStr();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string 	= 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$nonceStr.'&timestamp='.$timestamp.'&url='.$url;
		$signature 	= sha1($string);
		$signPackage= array(
				"appId"   => $this->appId,
				"nonceStr" => $nonceStr,
				"timestamp" => (string)$timestamp,
				"signature" => $signature,
				"string"	=> $string,
		);
		return $signPackage;
	}
	
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
	
	// 获取jsticket 两小时有效
	private function getJsApiTicket(){ // 只允许本类调用，继承的都不可以调用，公开调用就更不可以了
		$accessToken = $this->getAccessToken();
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$accessToken."&type=jsapi"; // 两小时有效
		$rurl = file_get_contents($url);
		$rurl = json_decode($rurl,true);
		if($rurl['errcode'] != 0){
			return false;
		}else{
			$jsticket = $rurl['ticket'];
			return $jsticket;
		}
	}
	
	private function getAccessToken() {
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret='.$this->appSecret;
		$res = json_decode($this->httpGet($url));
		$access_token = $res->access_token;
		return $access_token;
	}
	
	/**
	 * 利用微信接口开发上传图片到七牛
	 */
	public function getWeixinpicture($media_id){
		$weixin_token = $this->getAccessToken();
		// 从微信服务器下载
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$weixin_token."&media_id=".$media_id;
		return $url;
	}
	
	/**
	 * curl请求数据
	 * @param 地址     $url
	 * @return string|mixed
	 */
	private function httpGet($url,$data = ''){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		if(!empty($data)){
			curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$data = curl_exec($curl);
		if (curl_errno($curl)) {
			return 'ERROR '.curl_error($curl);}
			curl_close($curl);
			return $data;
	}
	
	
	
	/**
	 * curl请求数据
	 * @param 地址     $url
	 * @return string|mixed
	 */
	private function https_request($url,$data = ''){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		if(!empty($data)){
			curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$data = curl_exec($curl);
		if (curl_errno($curl)) {
			return 'ERROR '.curl_error($curl);}
			curl_close($curl);
			return $data;
	}
	
	/**
	 * 发送自定义的模板消息
	 * @param $touser
	 * @param $template_id
	 * @param $url
	 * @param $data
	 * @param string $topcolor
	 * @return bool
	 */
	public function doSend($touser, $template_id, $url='', $data, $topcolor = '#7B68EE')
	{
		$template = array(
				'touser' => $touser,
				'template_id' => $template_id,
				'url' => $url,
				'topcolor' => $topcolor,
				'data' => $data
		);
		$json_template = json_encode($template);
		$accessToken = $this->getAccessToken();
		$request_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$accessToken;
		$dataRes = $this->https_request($request_url, urldecode($json_template));
		return json_decode($dataRes);
	}
	
	
}